<template>
  <div class="student-exam-detail">
    <div class="header">
      <h3>成绩: {{ detail.score }} / {{ detail.totalScore }}</h3>
      <div v-if="detail.passScore" class="pass-info">
        <span>及格分: {{ detail.passScore }}</span>
        <el-tag :type="isPass ? 'success' : 'danger'">
          {{ isPass ? '及格' : '不及格' }}
        </el-tag>
      </div>
    </div>

    <el-tabs>
      <el-tab-pane label="答题详情">
        <div v-for="(question, index) in detail.questionDetails" :key="question.questionId" class="question-item">
          <div class="question-header">
            <span class="question-index">第{{ index + 1 }}题</span>
            <span class="question-type">{{ question.typeName }}</span>
            <span class="question-score">
              得分: {{ question.score }} / {{ question.maxScore }}
              <el-tag
                :type="getScoreTagType(question.score, question.maxScore)"
                size="mini"
              >
                {{ getScorePercentage(question.score, question.maxScore) }}%
              </el-tag>
            </span>
          </div>

<!--          <div class="question-content" v-html="question.content"></div>-->
          <formula-renderer class="question-content" :html="question.content" />


          <div class="student-answer">
            <h4>学生答案:</h4>
            <div v-if="question.selectedOptionCodes" class="options-answer">
              <p>选择选项: {{ question.selectedOptionCodes }}</p>
            </div>
<!--            <div v-if="question.answerContent" v-html="question.answerContent" class="text-answer"></div>-->
            <formula-renderer v-if="question.answerContent" class="text-answer" :html="question.answerContent" />
          </div>

          <div v-if="question.comment" class="teacher-comment">
            <h4>教师评语:</h4>
            <p>{{ question.comment }}</p>
          </div>
        </div>
      </el-tab-pane>

      <el-tab-pane label="成绩分析">
        <div class="analysis-container">
          <div class="chart-row">
            <div class="chart-item">
              <h4>题型得分分布</h4>
              <div style="height: 300px;">
                <div v-if="statistics.typeScores && statistics.typeScores.length">
                  <div ref="roseChart" style="width: 530px; height: 280px;"></div>
                </div>
                <el-empty v-else description="暂无题型得分数据" />
              </div>
            </div>
            <div class="chart-item">
              <h4>难度得分分布</h4>
              <div style="height: 300px;">
                <div v-if="statistics.difficultyScores && statistics.difficultyScores.length">
                  <div class="ring-chart-container">
                    <div v-for="(item, index) in statistics.difficultyScores" :key="index" class="ring-chart-item">
                      <div class="ring-chart">
                        <el-progress
                          type="circle"
                          :percentage="item.percentage.toFixed(2)"
                          :color="getDifficultyColor(item.difficulty)"
                          :width="80"
                        />
                      </div>
                      <div class="ring-chart-label">
                        <span>{{ item.difficultyName }}</span>
                        <span>{{ item.totalScore.toFixed(2) }} / {{ item.maxScore.toFixed(2) }}</span>
                      </div>
                    </div>
                  </div>
                </div>
                <el-empty v-else description="暂无难度得分数据" />
              </div>
            </div>
          </div>

          <div class="knowledge-analysis">
            <h4>知识点掌握情况</h4>
            <div v-if="statistics.knowledgeScores && statistics.knowledgeScores.length">
              <div ref="heatmapChart" style="width: 1500px; height: 600px;"></div>
            </div>
            <el-empty v-else description="暂无知识点数据" />
          </div>
        </div>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script>
import {
  getTeacherExamDetail,
  getTeacherExamStatistics
} from '@/api/exam/score'
import * as echarts from 'echarts'
import FormulaRenderer from "@/components/FormulaRenderer/index.vue";

export default {
  name: 'StudentExamDetail',
  components: {FormulaRenderer},
  props: {
    recordId: {
      type: Number,
      required: true
    }
  },
  data() {
    return {
      detail: {
        score: 0,
        totalScore: 100,
        passScore: 60,
        questionDetails: []
      },
      statistics: {
        typeScores: [],
        difficultyScores: [],
        knowledgeScores: []
      }
    }
  },
  computed: {
    isPass() {
      return this.detail.score >= this.detail.passScore
    }
  },
  created() {
    this.getDetail()
    this.getStatistics()
  },
  mounted() {
    this.$nextTick(() => {
      if (this.statistics.typeScores?.length) this.initRoseChart()
      if (this.statistics.knowledgeScores?.length) this.initHeatmapChart()
    })
  },
  methods: {
    getDetail() {
      getTeacherExamDetail(this.recordId).then(response => {
        this.detail = response.data
      })
    },

    getStatistics() {
      getTeacherExamStatistics(this.recordId).then(response => {
        this.statistics = response.data

        // 确保难度得分数据包含所有可能的难度级别
        const difficulties = [1, 2, 3, 4, 5]
        const difficultyNames = {
          1: '容易',
          2: '偏易',
          3: '中等',
          4: '偏难',
          5: '困难'
        }

        if (!this.statistics.difficultyScores) {
          this.statistics.difficultyScores = []
        }

        // 补全缺失的难度级别
        difficulties.forEach(diff => {
          const exists = this.statistics.difficultyScores.some(item => item.difficulty === diff)
          if (!exists) {
            this.statistics.difficultyScores.push({
              difficulty: diff,
              difficultyName: difficultyNames[diff],
              totalScore: 0,
              maxScore: 0,
              percentage: 0
            })
          }
        })

        // 按难度排序
        this.statistics.difficultyScores.sort((a, b) => a.difficulty - b.difficulty)

        this.$nextTick(() => {
          if (this.statistics.typeScores?.length) this.initRoseChart()
          if (this.statistics.knowledgeScores?.length) this.initHeatmapChart()
        })
      })
    },

    initRoseChart() {
      const chart = echarts.init(this.$refs.roseChart)
      const option = {
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c}% ({d}%)'
        },
        legend: {
          top: 'bottom',
          data: this.statistics.typeScores.map(item => item.typeName)
        },
        series: [
          {
            name: '题型得分率',
            type: 'pie',
            radius: [20, 100],
            center: ['50%', '50%'],
            roseType: 'area',
            itemStyle: {
              borderRadius: 5
            },
            label: {
              show: true,
              formatter: '{b}: {d}%'
            },
            emphasis: {
              label: {
                show: true
              }
            },
            data: this.statistics.typeScores.map(item => ({
              value: item.percentage,
              name: item.typeName,
              itemStyle: {
                color: this.getRandomColor()
              }
            }))
          }
        ]
      }
      chart.setOption(option)
      window.addEventListener('resize', () => chart.resize())
    },

    initHeatmapChart() {
      // 检查数据
      if (!this.statistics.knowledgeScores || this.statistics.knowledgeScores.length === 0) {
        console.warn('No knowledge score data available');
        return;
      }

      // 准备数据 - 确保格式正确
      const heatmapData = this.statistics.knowledgeScores.map(item => {
        // 确保percentage是数值且范围正确
        let percentage = Number(item.percentage);
        if (percentage <= 1) percentage = percentage * 100; // 如果是小数转换为百分比

        return {
          value: [0, item.knowledgeName, percentage], // 注意这里的格式
          itemStyle: {
            color: this.getHeatmapColor(percentage)
          },
          // 保存原始数据以便在tooltip中使用
          meta: {
            knowledgeName: item.knowledgeName,
            totalScore: item.totalScore,
            maxScore: item.maxScore,
            percentage: percentage
          }
        };
      });

      // 获取所有知识点名称（y轴数据）
      const knowledgeNames = [...new Set(
        heatmapData.map(item => item.value[1])
      )];

      // 初始化图表
      const chart = echarts.init(this.$refs.heatmapChart);
      const option = {
        tooltip: {
          position: 'top',
          formatter: params => {
            // 使用meta中的数据而不是直接访问数组
            const meta = params.data.meta;
            return `
          <strong>${meta.knowledgeName}</strong><br/>
          得分率: ${meta.percentage.toFixed(2)}%<br/>
          得分: ${meta.totalScore} / ${meta.maxScore}
        `;
          }
        },
        grid: {
          height: '80%',
          top: '10%',
          left: '3%',
          right: '4%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: ['掌握程度'], // x轴只有一个分类
          splitArea: { show: true }
        },
        yAxis: {
          type: 'category',
          data: knowledgeNames, // y轴显示知识点名称
          splitArea: { show: true },
          axisLabel: {
            interval: 0,
            rotate: 30 // 旋转标签防止重叠
          }
        },
        visualMap: {
          min: 0,
          max: 100,
          calculable: true,
          orient: 'horizontal',
          left: 'center',
          bottom: '0%',
          inRange: {
            color: ['#F56C6C', '#E6A23C', '#67C23A'] // 红-黄-绿渐变
          }
        },
        series: [{
          name: '知识点掌握情况',
          type: 'heatmap',
          data: heatmapData,
          label: {
            show: true,
            formatter: params => {
              // 直接从value数组中获取百分比值
              return params.value[2].toFixed(0) + '%';
            }
          },
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          }
        }]
      };

      chart.setOption(option);
      window.addEventListener('resize', () => chart.resize());
    },

    getRandomColor() {
      const colors = [
        '#5470C6', '#91CC75', '#FAC858', '#EE6666',
        '#73C0DE', '#3BA272', '#FC8452', '#9A60B4'
      ]
      return colors[Math.floor(Math.random() * colors.length)]
    },

    getDifficultyColor(difficulty) {
      const colors = {
        1: '#67C23A', // 容易 - 绿色
        2: '#95D475', // 偏易 - 浅绿
        3: '#E6A23C', // 中等 - 黄色
        4: '#F78989', // 偏难 - 浅红
        5: '#F56C6C'  // 困难 - 红色
      }
      return colors[difficulty] || '#909399'
    },

    getHeatmapColor(percentage) {
      if (percentage >= 80) return '#67C23A'
      if (percentage >= 60) return '#E6A23C'
      return '#F56C6C'
    },

    getScoreTagType(score, maxScore) {
      if (maxScore === 0) return 'info'
      const percentage = (score / maxScore) * 100
      if (percentage >= 80) return 'success'
      if (percentage >= 60) return 'warning'
      return 'danger'
    },

    getScorePercentage(score, maxScore) {
      if (maxScore === 0) return 0
      return Math.round((score / maxScore) * 100)
    }
  },
  beforeDestroy() {
    window.removeEventListener('resize', () => {})
  }
}
</script>

<style scoped>
.student-exam-detail {
  padding: 20px;
}

.header {
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
}

.header h3 {
  margin: 0 0 10px 0;
  font-size: 18px;
}

.pass-info {
  display: flex;
  align-items: center;
}

.pass-info span {
  margin-right: 10px;
}

.question-item {
  margin-bottom: 30px;
  padding: 15px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
}

.question-header {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px dashed #eee;
}

.question-index {
  font-weight: bold;
  margin-right: 15px;
}

.question-type {
  color: #666;
  margin-right: 15px;
}

.question-score {
  margin-left: auto;
}

.question-content {
  margin-bottom: 15px;
}

.student-answer {
  margin: 15px 0;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.student-answer h4 {
  margin: 0 0 10px 0;
  font-size: 14px;
  color: #666;
}

.options-answer {
  margin-top: 10px;
}

.text-answer {
  margin-top: 10px;
}

.teacher-comment {
  margin-top: 15px;
  padding: 15px;
  background-color: #f0f9eb;
  border-radius: 4px;
}

.teacher-comment h4 {
  margin: 0 0 10px 0;
  font-size: 14px;
  color: #67C23A;
}

.analysis-container {
  margin-top: 20px;
}

.chart-row {
  display: flex;
  margin-bottom: 30px;
}

.chart-item {
  flex: 1;
  padding: 15px;
  margin: 0 10px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
}

.chart-item h4 {
  margin: 0 0 15px 0;
  text-align: center;
}

.knowledge-analysis {
  margin-top: 20px;
}

.knowledge-analysis h4 {
  margin: 0 0 15px 0;
}

.ring-chart-container {
  display: flex;
  justify-content: space-around;
  flex-wrap: wrap;
}

.ring-chart-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin: 10px;
}

.ring-chart-label {
  margin-top: 10px;
  text-align: center;
}

.ring-chart-label span {
  display: block;
  font-size: 12px;
}
</style>
